package com.bxd.baodan.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.bxd.baodan.App;
import com.bxd.baodan.R;
import com.bxd.baodan.app.Constant;
import com.bxd.baodan.app.JsonApi;
import com.bxd.baodan.item.DesignCrInfoJSONBean;
import com.bxd.baodan.item.FamReportBean;
import com.bxd.baodan.item.GroupBean;
import com.bxd.baodan.item.LayoutBean;
import com.bxd.baodan.util.GsonUtil;
import com.bxd.baodan.util.NetUtil;
import com.bxd.baodan.util.StringUtil;
import com.bxd.baodan.widget.MyTextWatcher;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.List;

public class DelMemeberActivity extends BaseActivity {

    private DesignCrInfoJSONBean bean;
    private ListView lv;

    private MAdapter adapter;
    private List<GroupBean> list = new ArrayList<>();
    ;
    List<LayoutBean> layouts = new ArrayList<>();
    String[] homeSpendStrs = new String[4];
    String[] homeSpend = new String[4];


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_family_design);
        setActionBarTitle("删除成员");

        findViewById(R.id.bar_iv_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                showExitDialog("确认退出删除成员吗?");

            }
        });

        String data = getIntent().getStringExtra("fam_info");
        bean = (DesignCrInfoJSONBean) GsonUtil.fromJson(data, DesignCrInfoJSONBean.class);
        lv = findViewById(R.id.lv);

        adapter = new MAdapter(this, list);

        setListener();
        lv.setAdapter(adapter);


        GroupBean first = new GroupBean();
        first.middleVisible = true;
        first.layout = R.layout.family_del_start;
        list.add(first);
        adapter.notifyDataSetChanged();


    }

    private void setListener() {
        adapter.setListener(new FamilyDesignActivity.OkListener() {
            @Override
            public void next(int position, GroupBean nextBean) {

                GroupBean current = list.get(position);
                current.leftVisible = true;
                current.rightVisible = true;
                current.middleVisible = false;

                nextBean.leftVisible = true;
                nextBean.rightVisible = true;
                nextBean.middleVisible = true;


                if (current.layout == R.layout.family_del_start) {
                    list.remove(current);
                }


                list.add(nextBean);
                adapter.notifyDataSetChanged();
                lv.smoothScrollToPosition(adapter.getCount() - 1);


            }


            @Override
            public void pre(int position) {


            }
        });
    }


    class MAdapter extends BaseAdapter {
        private List<GroupBean> list;
        private Context context;
        private FamilyDesignActivity.OkListener listener;


        MAdapter(Context context, List<GroupBean> list) {
            this.list = list;
            this.context = context;
        }


        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int i) {
            return list.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(final int i, View view, ViewGroup viewGroup) {

            final ViewHolder holder;
            final GroupBean item = list.get(i);
            if (view == null) {
                view = View.inflate(DelMemeberActivity.this, R.layout.design_list_item, null);
                holder = new ViewHolder();
                view.setTag(holder);
            } else {
                holder = (ViewHolder) view.getTag();
            }
            holder.left = (TextView) view.findViewById(R.id.left);
            holder.right = (TextView) view.findViewById(R.id.right);
            holder.middle = (LinearLayout) view.findViewById(R.id.middle);
            holder.wait_layout = (RelativeLayout) view.findViewById(R.id.wait_layout);

            holder.left.setVisibility(item.leftVisible ? View.VISIBLE : View.GONE);
            holder.right.setVisibility(item.rightVisible ? View.VISIBLE : View.GONE);
            holder.middle.setVisibility(item.middleVisible ? View.VISIBLE : View.GONE);
            holder.wait_layout.setVisibility(View.GONE);


            holder.left.setText(item.left);
            holder.right.setText(item.right);
            ViewGroup mid = (ViewGroup) View.inflate(context, item.layout, null);


            holder.middle.removeAllViews();
            holder.middle.addView(mid);

            if (item.middleVisible) {


                try {
                    if (layouts != null && layouts.size() > 0) {
                        TextView title = ((TextView) mid.findViewById(R.id.title));
                        title.setText(layouts.get(i - 1).text);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }


                try {
                    mid.findViewById(R.id.finish).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {


                            String json = GsonUtil.toJson(bean.memberInfos);


                            NetUtil netUtil = new NetUtil(DelMemeberActivity.this, JsonApi.DESIGN_FAMILY);

                            netUtil.setParams("familyInfo", json);
                            netUtil.setParams("action", "doReport");


                            netUtil.setParams("familyAnnualIncome", homeSpend[0]);
                            netUtil.setParams("familyMonthSpending", homeSpend[1]);
                            netUtil.setParams("familyMonthAlimony", homeSpend[2]);
                            netUtil.setParams("familyLoan", homeSpend[3]);

                            netUtil.postRequest("正在生成报告", new NetUtil.RequestStringListener() {
                                @Override
                                public void onComplete(String result) {
                                    FamReportBean bean = new Gson().fromJson(result, FamReportBean.class);
                                    MobclickAgent.onEvent(App.getContext(), "v6_0_0_SY_znfasj_jt_ckbg");
                                    openActivity(WebViewPager.class, new String[]{"startUrl"}, new String[]{bean.data.url});
                                    App.getContext().sendBroadcast(
                                            new Intent(Constant.ACTION_SUCCESS_FAMILY_REPORT_SUCESS));
                                    finish();
                                }
                            });

                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }


                switch (item.layout) {


                    case R.layout.family_item_home_income:
                        parseHomeIncome(item, mid);
                        break;
                }


                mid.findViewById(R.id.next).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {


                        GroupBean nextBean = new GroupBean();
                        if (layouts != null && layouts.size() > 0 && i < layouts.size()) {
                            nextBean.member = layouts.get(i).member;
                            nextBean.name = layouts.get(i).text;
                            nextBean.left = layouts.get(i - 1).text;
                            nextBean.layout = layouts.get(i).layout;
                        }

                        switch (item.layout) {
                            case R.layout.family_del_start:
                                nextBean.left = "请重新输入您的家庭收支,以便更新您的家庭保障状态~";
                                nextBean.right = "开始吧";
                                nextBean.layout = R.layout.family_item_home_income;

                                break;


                            case R.layout.family_item_home_income:
                                StringBuilder stringBuilder = new StringBuilder();

                                for (String homeSpendStr : homeSpendStrs) {
                                    if (StringUtil.isEmpty(homeSpendStr)) {
                                        showToast("请填写所有信息");
                                        return;
                                    }
                                    stringBuilder.append(homeSpendStr);
                                }
                                nextBean.left = "您的家庭收支";
                                nextBean.right = stringBuilder.toString();
                                nextBean.layout = R.layout.family_item_finish;
                                break;
                        }
                        listener.next(i, nextBean);
                    }
                });

            }

            return view;
        }

        public void setListener(FamilyDesignActivity.OkListener listener) {
            this.listener = listener;
        }

        public class ViewHolder {
            TextView left;
            TextView right;
            LinearLayout middle;
            RelativeLayout wait_layout;
        }


    }

    private void parseHomeIncome(final GroupBean item, ViewGroup mid) {

        for (int i = 0; i < homeSpendStrs.length; i++) {
            homeSpendStrs[i] = "";
            homeSpend[i] = "";
        }
        mid.findViewById(R.id.bar_iv_close).setVisibility(View.INVISIBLE);

        //年收入
        final EditText year = (EditText) mid.findViewById(R.id.family_annual_income);
        //月收入
        final EditText mouth = (EditText) mid.findViewById(R.id.family_month_spending);
        //赡养金
        final EditText alimony = (EditText) mid.findViewById(R.id.family_month_alimony);
        //贷款
        final EditText loan = (EditText) mid.findViewById(R.id.family_loan);

        year.setText(bean.familyAnnualIncome);
        mouth.setText(bean.familyMonthSpending);
        alimony.setText(bean.familyMonthAlimony);
        loan.setText(bean.familyLoan);

//        netUtil.setParams("familyAnnualIncome", homeSpend[0]);
//        netUtil.setParams("familyMonthSpending", homeSpend[1]);
//        netUtil.setParams("familyMonthAlimony", homeSpend[2]);
//        netUtil.setParams("familyLoan", homeSpend[3]);
        homeSpend[0] = year.getText().toString().trim();
        homeSpendStrs[0] = "家庭年收入:  " + year.getText().toString().trim() + "万元\n";

        homeSpend[1] = mouth.getText().toString().trim();
        homeSpendStrs[1] = "家庭月开销:  " + mouth.getText().toString().trim() + "元/月\n";


        homeSpend[2] = alimony.getText().toString().trim();
        homeSpendStrs[2] = "赡养金:  " + alimony.getText().toString().trim() + "元/月\n";

        homeSpend[3] = loan.getText().toString().trim();
        homeSpendStrs[3] = "待偿还贷款:  " + loan.getText().toString().trim() + "万元";

        year.addTextChangedListener(new MyTextWatcher() {
            @Override
            public void afterTextChanged(Editable s) {

                // info.family_annual_income = year.getText().toString().trim();
                homeSpend[0] = year.getText().toString().trim();
                homeSpendStrs[0] = "家庭年收入:  " + year.getText().toString().trim() + "万元\n";

            }
        });


        mouth.addTextChangedListener(new MyTextWatcher() {
            @Override
            public void afterTextChanged(Editable s) {
                //  info.family_month_spending = mouth.getText().toString().trim();
                homeSpend[1] = mouth.getText().toString().trim();
                homeSpendStrs[1] = "家庭月开销:  " + mouth.getText().toString().trim() + "元/月\n";
            }
        });


        alimony.addTextChangedListener(new MyTextWatcher() {
            @Override
            public void afterTextChanged(Editable s) {
                // info.family_month_alimony = alimony.getText().toString().trim();
                homeSpend[2] = alimony.getText().toString().trim();
                homeSpendStrs[2] = "赡养金:  " + alimony.getText().toString().trim() + "元/月\n";
            }
        });


        loan.addTextChangedListener(new MyTextWatcher() {
            @Override
            public void afterTextChanged(Editable s) {

                // fixme 修复没有贷款,写错变量了
                //   info.family_loan = loan.getText().toString().trim();
                homeSpend[3] = loan.getText().toString().trim();
                homeSpendStrs[3] = "待偿还贷款:  " + loan.getText().toString().trim() + "万元";
            }
        });


    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            showExitDialog("确认退出删除成员吗?");
            return false;
        } else {
            return super.onKeyDown(keyCode, event);
        }

    }
}
